package logic

import (
	"ball/ballrpc/ballrpc"
	"ball/ballrpc/internal/svc"
	"ball/models/mysql"
	"context"

	"github.com/zeromicro/go-zero/core/logx"
)

type PostListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPostListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PostListLogic {
	return &PostListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 帖子列表
func (l *PostListLogic) PostList(in *ballrpc.PostListRequest) (*ballrpc.PostListResponse, error) {
	// todo: add your logic here and delete this line
	var post []mysql.Post
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	mysql.DB.Debug().Limit(int(pageSize)).Offset(int(offset)).Order("title desc").Find(&post)

	var PostList []*ballrpc.PostList
	for _, m := range post {
		list := ballrpc.PostList{
			Title: m.Title,
			Desc:  m.Desc,
		}
		PostList = append(PostList, &list)
	}
	return &ballrpc.PostListResponse{
		List: PostList,
	}, nil
}
